package fr.ordre66.vlcs.security;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;

import fr.ordre66.vlcs.dto.User;
import fr.ordre66.vlcs.services.IUserManager;

public class VlcsAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider{

	@Autowired IUserManager userManager;
	
	@Override
	protected void additionalAuthenticationChecks(UserDetails arg0,
			UsernamePasswordAuthenticationToken arg1)
			throws AuthenticationException {
		// TODO Auto-generated method stub
	}

	@Override
	protected UserDetails retrieveUser(String arg0,
			UsernamePasswordAuthenticationToken auth)
			throws AuthenticationException {
		
		String login = (String) auth.getPrincipal();
		User user = userManager.get(login);
		
		if(user== null)
			throw new AuthenticationCredentialsNotFoundException("User not found");
		
		return buildUserFromUserEntity(user);
	}

	org.springframework.security.core.userdetails.User buildUserFromUserEntity(User user) {

		String username = user.getLogin();
		String password = user.getPassword();

		Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		authorities.add(new GrantedAuthorityImpl("ROLE_USER"));

		org.springframework.security.core.userdetails.User userSpringS = new org.springframework.security.core.userdetails.User(username, password, true, true, true, true, authorities);
		return userSpringS;
	}

}
